import { login, logout, getUserInfo } from '@/api/auth'
import { getToken, setToken, removeToken } from '@/utils/auth'

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  roles: [],
  permissions: [],
  info: null,
  isFetching: false // 添加请求状态锁
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_PERMISSIONS: (state, permissions) => {
    state.permissions = permissions
  },
  SET_FETCHING: (state, isFetching) => {
    state.isFetching = isFetching
  }
}

const actions = {
  // 用户登录
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password })
        .then(response => {
          const { data } = response
          commit('SET_TOKEN', data.token)
          setToken(data.token)
          resolve()
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // 获取用户信息
  getInfo({ commit, state }) {
    if (state.isFetching) return // 阻止重复请求
    return new Promise((resolve, reject) => {
      getUserInfo()
        .then(response => {
          const { data } = response
          
          if (!data) {
            reject('获取用户信息失败，请重新登录')
          }

          const { user, permissions } = data
          commit('SET_FETCHING', true)
          // 保存用户信息
          commit('SET_NAME', user.name)
          commit('SET_AVATAR', user.avatar || '')
          
          // 保存权限信息
          commit('SET_PERMISSIONS', permissions || [])
          
          resolve(data)
          commit('SET_FETCHING', false)
        })
        .catch(error => {
          reject(error)
          commit('SET_FETCHING', false)
        })
    })
  },

  // 用户登出
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout()
        .then(() => {
          commit('SET_TOKEN', '')
          commit('SET_PERMISSIONS', [])
          removeToken()
          resolve()
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // 重置Token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_PERMISSIONS', [])
      removeToken()
      resolve()
    })
  },
  
  async changePassword({ commit }, payload) {
    // 调用实际的后端API
    const { data } = await axios.put('/api/user/change-password', payload)
    return data
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
} 